package cn.xiaopengstack.trigger.http;

import cn.xiaopengstack.api.dto.AiAgentRequestDTO;
import cn.xiaopengstack.api.service.IAiAgentService;
import cn.xiaopengstack.domain.agent.model.entity.ExecuteCommandEntity;
import cn.xiaopengstack.domain.agent.service.dispatch.impl.AgentDispatchService;
import cn.xiaopengstack.domain.agent.service.execute.IExecuteStrategy;
import cn.xiaopengstack.domain.agent.service.execute.auto.AutoAgentExecuteStrategy;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author jiangyangang
 */
@RestController
@Slf4j
@RequestMapping("/api/${spring.server.version}/agent/")
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class AiAgentController implements IAiAgentService {
    @Resource
    private AutoAgentExecuteStrategy executeStrategy;

    @Resource
    private AgentDispatchService agentDispatchService;

    @RequestMapping(value = "execute_agent", method = RequestMethod.POST)
    @Override
    public ResponseBodyEmitter executeAgent(@RequestBody AiAgentRequestDTO request, HttpServletResponse response) {
        try {
            log.info("Agent流式执行请求开始，request:{}", request);

            response.setContentType("test/event-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Connection", "keep-alive");
            // 创建流式输出对象
            ResponseBodyEmitter responseBodyEmitter = new ResponseBodyEmitter(Long.MAX_VALUE);

            // 构造智能体
            ExecuteCommandEntity commandEntity = ExecuteCommandEntity.builder()
                    .aiAgentId(request.getAiAgentId())
                    .message(request.getMessage())
                    .sessionId(request.getSessionId())
                    .maxSteps(request.getMaxStep())
                    .emitter(responseBodyEmitter)
                    .build();

            agentDispatchService.dispatch(commandEntity);

            return responseBodyEmitter;
        } catch (Exception e) {
            log.error("AutoAgent请求处理异常：{}", e.getMessage(), e);
            ResponseBodyEmitter errorEmitter = null;
            try {
                errorEmitter = new ResponseBodyEmitter();
                errorEmitter.send("请求处理异常：" + e.getMessage());
                errorEmitter.complete();
            } catch (IOException ex) {
                log.error("AutoAgent发送错误响应异常：{}", e.getMessage(), e);
            }
            return errorEmitter;
        }
    }
}
